﻿using SIG.InputModel.Admin.Identity;
using SIG.InputModel.Front.SetupWizard;
using SIG.Resources.Admin;
using SIG.Service.Identity;
using SIG.ViewModel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;



namespace SIG.WebMVC.Controllers
{
    public class SetupController : BaseController
    {
        IUserService _userService;
        IRoleService _roleService;
        public SetupController(IUserService UserService, IRoleService roleService)
        {
            _userService = UserService;
            _roleService = roleService;
        }
        // GET: Setup
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Install(SetupIM vm)
        {
            if (!ModelState.IsValid)
            {
                var errorMessage = GetModelErrorMessage();
                AR.Setfailure(errorMessage);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            try
            {
                SaveInfo(vm.SiteName);
                string constr = $"Data Source={vm.DatabaseServer.Trim()};Initial Catalog={vm.DatabaseName.Trim()};Persist Security Info=True;User ID={vm.DatabaseUser.Trim()};Password={vm.DatabasePassword.Trim()};MultipleActiveResultSets=true;";
                SaveDatabaseInfo(constr);
                SaveWebConfig(constr);
                //  UpdateDatabase(vm.DatabaseServer, vm.DatabaseName, vm.DatabaseUser, vm.DatabasePassword, vm.IsWithData);
                ViewBag.Constr = constr;
            }
            catch (Exception ex)
            {
                TempData["error"] = ex.Message;
            }

            SetupAdminIM adminVM = new SetupAdminIM
            {
                SiteName = vm.SiteName,
                DatabaseName = vm.DatabaseName,
                DatabaseServer = vm.DatabaseServer,
                DatabasePassword = vm.DatabasePassword,
                DatabaseUser = vm.DatabaseUser,
                IsWithData = vm.IsWithData
            };

            return View(adminVM);

        }

        [HttpPost]
        public async System.Threading.Tasks.Task<ActionResult> Complate(SetupAdminIM vm)
        {
            if (!ModelState.IsValid)
            {
                var errorMessage = GetModelErrorMessage();
                AR.Setfailure(errorMessage);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            try
            {

                UpdateDatabase(vm.DatabaseServer, vm.DatabaseName, vm.DatabaseUser, vm.DatabasePassword, vm.IsWithData);
                var result = _userService.Register(vm.AdminUser, vm.AdminEmail, vm.AdminPassword, string.Empty);

                var user = await _userService.GetUserByName(vm.AdminUser);
                var role = _roleService.FindBy(r => r.RoleName.Equals("创始人")).FirstOrDefault();
                user.Roles.Clear();
                user.Roles.Add(role);
                _userService.Update(user);

                
            }
            catch (Exception ex)
            {
                TempData["error"] = ex.Message;
            }

            return View();

        }

        private void SaveInfo(string siteName)
        {
            var xmlFile = Server.MapPath("~/Config/GlobalSettings.config");
            XDocument doc = XDocument.Load(xmlFile);
            var item = doc.Descendants("Settings").FirstOrDefault();
            item.Element("SiteName").SetValue(siteName);
            doc.Save(xmlFile);
        }

        private void SaveDatabaseInfo(string connStr)
        {
            var xmlFile = Server.MapPath("~/Config/log4net.config");
            XDocument doc = XDocument.Load(xmlFile);
            var item = doc.Descendants("log4net").FirstOrDefault();
            item.Element("appender").Element("connectionString").SetAttributeValue("value", connStr);
            doc.Save(xmlFile);
        }
        private void SaveWebConfig(string connStr)
        {
            Configuration myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            myConfiguration.ConnectionStrings.ConnectionStrings["SigContext"].ConnectionString = connStr;
            //myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text
            myConfiguration.Save();
        }

        private void UpdateDatabase(string server,string databaseName,string userId,string password,bool IsWithData)
        {
            string constr = $"Data Source={server.Trim()};Initial Catalog={databaseName.Trim()};Persist Security Info=True;User ID={userId.Trim()};Password={password.Trim()};MultipleActiveResultSets=true;";
   
            SqlConnection conn = new SqlConnection(constr);          
            conn.Open();
                var sqlPath = IsWithData ? Server.MapPath("~/App_Data/InstallWithData.sql") : Server.MapPath("~/App_Data/Install.sql");
                string script = System.IO.File.ReadAllText(sqlPath);
                // split script on GO command
                IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                foreach (string commandString in commandStrings)
                {
                    if (commandString.Trim() != "")
                    {
                        new SqlCommand(commandString, conn).ExecuteNonQuery();
                    }
                }  
            conn.Close();
        }


    }
}